package com.csis.framework.util;

import java.util.List;

import com.csis.framework.domain.Page;

public abstract class XmlGrid implements Grid {
	private Page page = null;
	private StringBuffer buffer = new StringBuffer();

	public XmlGrid(Page page) {
		this.page = page;
	}

	/* (non-Javadoc)
	 * @see com.csis.framework.util.Grid#doProcess(java.util.List)
	 */
	@Override
	public <T> String doProcess(List<T> objs) {
		genHeader();
		int count = 0;
		for (T t : objs) {
			buffer.append("<row id='").append(getId(t)).append("'>");
			String[] columns = genRow(t);
			buffer.append("<cell>").append((page.getCurPage() - 1) * page.getCount() + ++count).append("</cell>");
			for (String cell : columns)
				buffer.append("<cell><![CDATA[").append(cell).append("]]></cell>");
			buffer.append("</row>");
			genRow(t);
		}
		buffer.append("</rows>");
		return buffer.toString();
	}

	public abstract String[] genRow(Object o);

	public abstract String getId(Object o);

	private void genHeader() {
		buffer.append("<?xml version='1.0' encoding='UTF-8'?>");
		buffer.append("<rows>");
		buffer.append("<page>").append(page.getCurPage()).append("</page>");
		buffer.append("<total>").append(page.getMaxPage()).append("</total>");
		buffer.append("<records>").append(page.getMaxCount()).append("</records>");
	}
}
